package com.cet.algorithm.栈与队列;

import java.util.ArrayDeque;

/**
 * @program: algorithm
 * @description: 用栈实现队列
 * @author: 陈恩涛
 * @create: 2022-07-11 15:36
 **/
public class LC232 {

    public static void main(String[] args) {
        final MyQueue<Integer> myQueue = new MyQueue<>();
        myQueue.push(1);
        myQueue.push(2);
        System.out.println(myQueue.peek());
        System.out.println(myQueue.pop());
        System.out.println(myQueue.empty());
    }

}

class MyQueue<T> {

    /**
     * 第一个栈
     */
    private final ArrayDeque<T> head;

    /**
     * 第二个栈
     */
    private final ArrayDeque<T> tail;

    /**
     * 队列中元素的个数
     */
    private int length;

    public MyQueue() {
        this.head = new ArrayDeque<>();
        this.tail = new ArrayDeque<>();
        this.length = 0;
    }

    /**
     * 队列是否为空
     * @return 结果
     */
    boolean empty() {
        return length == 0;
    }

    void push(T e) {
        tail.addFirst(e);
        length++;
    }

    T pop() {
        if (empty()) {
            throw new UnsupportedOperationException("Sorry! Queue is empty!");
        }
        if (head.size() == 0) {
            move();
        }
        length--;
        return head.pop();
    }

    /**
     * 将尾部的元素倒序移动到头部
     */
    private void move() {
        while (!tail.isEmpty()) {
            head.addFirst(tail.pop());
        }
    }

    T peek() {
        if (empty()) {
            throw new UnsupportedOperationException("Sorry! Queue is empty!");
        }
        if (head.size() == 0) {
            move();
        }
        return head.peek();
    }

}
